<template>
  <div class="Content">
    <form-view
      class="task-tab-container task-view-containner"
      :fields="taskfields"
      :value="taskValue"
    >
      <!-- 审批编号 -->
      <template slot="paasNo" slot-scope="{ field, value }">
        <div class="form-view-row">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <span @click="OpenPass" class="link">{{ value }}</span>
          </div>
        </div>
      </template>
      <!-- 审批状态 -->
      <template slot="paasState" slot-scope="{ field, value }">
        <div class="form-view-row">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <span>{{ paasState[value] }}</span>
          </div>
        </div>
      </template>
      <!-- 结算明细 工时服务费 补贴费 里程费合并为结算明细 start-->
      <template slot="settlementDetail" slot-scope="{ field, value }">
        <div class="form-view-row">
          <label>{{ field.displayName }}</label>
          <div v-if="feeRecordData.length" class="form-view-row-content">
            <el-table
              :data="feeRecordData"
              border
              style="width: 100%">
              <el-table-column
                :label="$t('common.base.SN')"
                type="index"
                width="50">
              </el-table-column>
              <el-table-column
                v-for="(column, index) in feeColumn"
                :key="`${column.fieldName}_${index}`"
                :prop="column.fieldName"
                :label="column.displayName"
                show-overflow-tooltip>

                <el-table-column
                  v-for="(childColumn, childIndex) in column.children"
                  :key="`${childColumn.fieldName}_${childIndex}`"
                  :prop="childColumn.fieldName"
                  :label="childColumn.displayName"
                  show-overflow-tooltip
                  min-width="200">
                </el-table-column>

              </el-table-column>
            </el-table>
          </div>
        </div>
      </template>
      <!-- 结算明细 end-->
      <!-- 其他费用 -->
      <template slot="otherFee" slot-scope="{ field, value }">
        <div class="form-view-row">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">{{ SetFormat(value) }}</div>
        </div>
      </template>
      <!-- 总费用 -->
      <template slot="sumAmount" slot-scope="{ field, value }">
        <div class="form-view-row">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <span class="Sum">{{ SetFormat(value) }}</span>
          </div>
        </div>
      </template>
    </form-view>
    <!-- 手动结算灰度与权限  -->
    <el-button
      v-if="providerSettleV2 && provideSettleConfig.taskSettleBtn"
      type="primary"
      @click="OpenSettlement"
      style="margin-left: 12px"
      >提交服务商结算</el-button
    >
    <el-button
      v-if="isTaskExtra"
      style="margin-left: 12px"
      type="primary"
      @click="OpenPass"
      >查看审批单</el-button
    >
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';

export default {
  name: 'settlementTab',

  props: {
    providerSettleV2: {
      type: Boolean,
      default: false,
    },
    provideSettleConfig: {
      type: Object,
      default: () => {
        return {
          taskSettleBtn: false,
        };
      },
    },
    // 工单数据与权限
    shareData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      paasState: {
        1: '进行中',
        2: '已完成',
        3: '已取消',
        4: '草稿',
      },
      isOpenData,
      taskValue: {},
      taskfields: [],
      isTaskExtra: false,
      // 结算明细
      feeColumn: [],
      feeRecordData: [],
      StartFields: [
        {
          typeId: 2,
          fieldName: 'paasNo',
          displayName: '审批编号',
          formType: 'number',
          isSystem: 1,
          orderId: 0,
        },
        {
          typeId: 2,
          fieldName: 'paasState',
          displayName: '审批状态',
          formType: 'number',
          isSystem: 1,
          orderId: 0,
        },
      ],
    };
  },

  mounted() {
    this.GetOneTaskExtra();
    this.GetbuildFields();
  },

  methods: {
    OpenSettlement() {
      this.$emit('open');
    },
    OpenPass() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePaasTemplateDetail,
        params: `formId=${this.taskValue.templateBizId}&formContentId=${this.taskValue.paasFormContentId}&processId=${this.taskValue.paasFormContentId.processorInstanceId}`,
        key: this.taskValue.paasFormContentId,
        titleKey: `结算${this.taskValue.paasNo}`,
      });
    },
    SetFormat(value) {
      // 空值判断
      if (['', undefined, null].includes(value)) {
        return '';
      }
      if (Number?.toLocaleString) {
        let options = {
          style: 'currency',
          currency: 'CNY',
        };
        return value?.toLocaleString(undefined, options);
      } else {
        return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }
    },
    GetbuildFields() {
      TaskApi.newbuildFields().then(res => { 
        if (res.code === 0 && res.result) {
          this.taskfields = [...this.StartFields, ...res.result];
        }
      });
    },
    GetOneTaskExtra() {
      let { id } = this.shareData.task;
      TaskApi.getOneTaskExtra({
        taskId: id,
      }).then(res => {
        this.isTaskExtra = !!res.result;
        if (res.code === 0 && res.result) {
          this.taskValue = res.result;
          if (!this.taskValue.attachment) {
            this.taskValue.attachment = [];
          }
          // 构建结算明细数据
          this.buildFeeRecordColumn(this.taskValue)
          this.$emit('saveData', this.taskValue);
        }
      });
    },
    // 处理结算明细数据列
    buildFeeRecordColumn(data) {
      const { feeRecord } = data;
      if(!feeRecord) return;
      // 工时服务费
      const hourlyServiceFeeKeys = Object.keys(feeRecord.hourlyServiceFee || {});
      const hourlyServiceFeeColumn = this.getFeeColumns(hourlyServiceFeeKeys, 'hourlyServiceFee');
      // 补贴费
      const subsidyFeeKeys = Object.keys(feeRecord.subsidyFee || {});
      const subsidyFeeColumn = this.getFeeColumns(subsidyFeeKeys, 'subsidyFee');
      // 里程费
      const mileageFeeColumn = this.getFeeColumns([], 'mileageFee');

      this.feeColumn = [
        {
          displayName: this.$t('common.form.preview.subForm.displayName.hourlyServiceFee'),
          fieldName: 'hourlyServiceFee',
          children: hourlyServiceFeeColumn
        },
        {
          displayName: this.$t('common.form.preview.subForm.displayName.subsidyFee'),
          fieldName: 'subsidyFee',
          children: subsidyFeeColumn
        },
        {
          displayName: this.$t('common.form.preview.subForm.displayName.mileageFee'),
          fieldName: 'mileageFee',
          children: mileageFeeColumn
        }
      ];
      
      this.buildFeeRecordData(data);
    },
    // 处理结算明细数据值
    buildFeeRecordData(data) {
      const { feeRecord, hourlyServiceFee, mileageFee, subsidyFee } = data;
      const hourlyServiceFeeValues = this.getFeeValues((feeRecord.hourlyServiceFee), 'hourlyServiceFee');
      const subsidyFeeValues = this.getFeeValues((feeRecord.subsidyFee), 'subsidyFee');
      const mileageFeeValues = this.getFeeValues((feeRecord.mileageFee), 'mileageFee');
      const feesMap = {
        ...hourlyServiceFeeValues,
        ...subsidyFeeValues,
        ...mileageFeeValues
      }
      this.feeRecordData = [{
        'hourlyServiceFee_total': hourlyServiceFee,
        'subsidyFee_total': subsidyFee,
        'mileageFee_total': mileageFee,
        ...feesMap,
      }];
      
      this.taskValue = {
        ...this.taskValue,
        ...feesMap
      };
      
    },
    getFeeValues(fees, type) {
      if(!fees) return {};
      const feeData = {};
      for(let fee in fees) {
        const feeKey = `${type}_${fee}`;
        feeData[feeKey] = fees[fee];
      }
      return feeData;
    },
    getFeeColumns(fees, type) {
      const feeColumns = fees.map(item => {
        return {
          displayName: item,
          fieldName: `${type}_${item}`,
        }
      });
      return [...feeColumns, ...[{ displayName: this.$t('common.base.amountCount'), fieldName: `${type}_total` }]]
    },  
  },
};
</script>

<style lang="scss" scoped>
.Content {
  position: relative;
  width: 100%;
}
.edit {
  position: absolute;
}
.state {
  height: 22px;
  background: #faaa14;
  border-radius: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 500;
  color: #ffffff;
  padding: 3px 8px;
  max-width: 70px;
}
.Sum {
  font-weight: bold;
}
.link {
  color: $color-primary-light-6;
  cursor: pointer;
}
</style>
